<script setup lang="ts">
import type { AgentTableData, PageTableRequestData } from "@/common/apis/intelligent/type"
import { getAgentDataApi, getAgentTypeOptionsApi, importApi } from "@/common/apis/intelligent"
import { agentSupportSideMap, FormTypeEnum } from "@@/constants/other-keys"
import { ElMessageBox } from "element-plus"
import { isEqual } from "lodash-es"
import { computed, ref, watch } from "vue"
import { usePagination } from "@/common/composables/usePagination"
import { Search } from "@element-plus/icons-vue"
import { getProjectId } from "@/common/utils/cache/local-storage"

interface Props {
  visible: boolean
}

const props = defineProps<Props>()
const emit = defineEmits(["closeDialog"])
const dialogVisible = ref<boolean>(false)
const loading = ref<boolean>(false)
const agentTypeOptions = ref<string[]>([])
const searchKey = ref()
const TableRef = ref()
const tableData = ref<AgentTableData[]>([])
const multipleSelection = ref<AgentTableData[]>([])
const { paginationData, handleSizeChange, handleCurrentChange } = usePagination()

const textMap = computed(() => {
  return "从资源库导入"
})
function getTableData() {
  loading.value = true
  const params: PageTableRequestData = {
    size: paginationData.pageSize,
    current_page: paginationData.currentPage,
    agent_name: searchKey.value,
    agent_type: undefined,
    create_time: undefined,
    end_time: undefined
  }
  getAgentDataApi(params)
    .then(({ data }) => {
      tableData.value = data.rows
      paginationData.total = data.total
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
function handleSearch() {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
function hanldeClearSelection() {
  nextTick(() => {
    TableRef.value.clearSelection()
  })
}

function showDialog() {
  handleSearch()
  handleAgentTypeOptions()
  hanldeClearSelection()
}
function closeDialog() {
  emit("closeDialog", undefined)
}

function handleConfirm() {
  if (multipleSelection.value.length < 1) {
    ElMessage.warning("请选择智能体")
    return
  }
  const ids = multipleSelection.value.map((item: any) => item.agent_id)
  const data = {
    project_id: getProjectId(),
    agent_ids: ids
  }
  importApi(data).then(() => {
    ElMessage.success("导入成功")
    emit("closeDialog", "refresh")
  })
}
function handleCloseTip(done: () => void) {
  if (multipleSelection.value.length < 1) {
    closeDialog()
    done()
    return
  }
  ElMessageBox.confirm("当前所选为导入，是否确定关闭？").then(() => {
    done()
  })
}

function handleAgentTypeOptions() {
  getAgentTypeOptionsApi().then(({ data }) => {
    agentTypeOptions.value = data.type
  })
}

function handleSelectionChange(val: AgentTableData[]) {
  multipleSelection.value = val
}
function getRowKeys(row: AgentTableData) {
  return row.agent_id
}
watch(
  () => [props.visible],
  () => {
    dialogVisible.value = props.visible
    if (props.visible) {
      showDialog()
    }
  }
)

watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>

<template>
  <el-drawer
    v-model="dialogVisible"
    direction="rtl"
    size="800px"
    @close-auto-focus="closeDialog"
    @close="closeDialog"
    :before-close="handleCloseTip"
    :show-close="false"
    :append-to-body="true"
  >
    <template #header>
      <div class="drawer-header">
        <h4>{{ textMap }}</h4>
      </div>
    </template>
    <template #default>
      <div class="drawer-body-lock">
        <div class="flex-between mb-main-padding">
          <el-text>
            已选择 {{ multipleSelection.length }} 个智能体，
            <el-link :underline="false" @click="hanldeClearSelection">清空选择</el-link>
          </el-text>
          <el-input v-model="searchKey" placeholder="请输入搜索内容" class="csc-search-input" style="width: 240px;" @keydown.enter="handleSearch">
            <template #append>
              <el-button :icon="Search" v-throttle="() => handleSearch()" />
            </template>
          </el-input>
        </div>
        <div class="cpi-content-main">
          <el-auto-resizer>
            <template #default="{ height, width }">
              <el-table
                ref="TableRef" v-loading="loading" :data="tableData" :row-key="getRowKeys" :width="width"
                :height="height" @selection-change="handleSelectionChange"
              >
                <el-table-column type="selection" header-align="left" :reserve-selection="true" width="55" />
                <el-table-column prop="agent_name" show-overflow-tooltip label="名称" header-align="left" />
                <el-table-column prop="agent_type" show-overflow-tooltip label="类型" header-align="left" />
                <el-table-column prop="agent_support_side" show-overflow-tooltip label="支持阵营" header-align="left">
                  <template #default="{ row }">
                    {{ agentSupportSideMap[row.agent_support_side] }}
                  </template>
                </el-table-column>
                <el-table-column prop="agent_describe" show-overflow-tooltip label="描述" header-align="left"/>
                <el-table-column prop="create_time" sortable label="时间" header-align="left" width="140" />
              </el-table>
            </template>
          </el-auto-resizer>
        </div>
        <div class="pager-wrapper">
          <el-pagination
            background
            layout="total, sizes, ->, prev, pager, next, jumper"
            :disabled="loading"
            :page-sizes="paginationData.pageSizes"
            :total="paginationData.total"
            :page-size="paginationData.pageSize"
            :current-page="paginationData.currentPage"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </template>
    <template #footer>
      <div class="dialog-footer">
        <el-button plain v-throttle="() => closeDialog()">
          取消
        </el-button>
        <el-button :loading="loading" type="primary" v-throttle="() => handleConfirm()">
          确定导入
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<style lang="scss" scoped>
.flex-between {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.pager-wrapper {
  width: 100% !important;
  background-color: transparent !important;
}
.drawer-body-lock {
  position: relative;
  padding-bottom: 60px;
}
.upload-demo {
  width: 100% !important;
}
:deep(.el-upload.el-upload--text) {
  width: 100% !important;
}
</style>
